<?php
/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 2016/11/24
 * Time: 下午2:04
 */

namespace common\services\myhtsq;


use common\entities\ConfigEntity;
use common\entities\myhtsq\ProjectContactEntity;
use common\error\ErrorInfo;
use common\repositories\common\MyscrmContractProjectRepository;
use common\repositories\common\MyscrmOrganizationRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\ProjectContactChangeLogRepository;
use common\repositories\myhtsq\ProjectContactRepository;
use common\repositories\myhtsq\ProjectRepository;
use common\services\BaseService;
use common\support\StringHelper;

class ProjectService extends BaseService
{
    /* @var $_projectContactRepository ProjectContactRepository */
    private $_projectContactRepository;

    /* @var $_contractProjectRepository MyscrmContractProjectRepository */
    private $_contractProjectRepository;

    /* @var $_changeLogRepository ProjectContactChangeLogRepository */
    private $_changeLogRepository;
    private $_projectRepository;


    public function __construct(ProjectContactRepository $projectContactRepository,
                                MyscrmContractProjectRepository $myscrmContractProjectRepository,
                                ProjectContactChangeLogRepository $projectContactChangeLogRepository,
                                ProjectRepository $projectRepository,
                                $config = [])
    {
        $this->_projectContactRepository = $projectContactRepository;
        $this->_contractProjectRepository = $myscrmContractProjectRepository;
        $this->_changeLogRepository = $projectContactChangeLogRepository;
        $this->_projectRepository = $projectRepository;
        parent::__construct($config);
    }

    /**
     * 获取交付顾问以及客户经理信息
     * @param $orgId
     * @param $projectId
     * @return array
     */
    public function getDeliverInfo($orgId, $projectId)
    {
        $result = [
            "custom_manage" => [],
            "deliver" => []
        ];
        $data = $this->_projectContactRepository->getList($orgId, $projectId);
        if (!empty($data)) {
            foreach ($data as $user) {
                $userGuid = $user["user_guid"];
                $userInfo = ErpUserRepository::getUserById($userGuid);
                if (empty($userInfo)) {
                    continue;
                }
                $item["name"] = $userInfo["UserName"];
                $item["user_guid"] = $userGuid;
                $item["mobile"] = StringHelper::getLastMobilePhone($userInfo["MobilePhone"]);
                $item["email"] = $userInfo["Email"];
                if ($user["user_type"] == ProjectContactEntity::USER_TYPE_DELIVER) {
                    //交付顾问
                    array_push($result["deliver"], $item);
                } else {
                    //客户经理
                    array_push($result["custom_manage"], $item);
                }
            }
        }
        if (!empty($result["custom_manage"]) && !empty($result["deliver"])) {
            return $result;
        }

        //如果project中是空的,则继承租户中的数据
        $org = MyscrmOrganizationRepository::getById($orgId);
        if (empty($result["custom_manage"]) && !empty($org["CustomManagerGUID"])) {
            $userGuid = $org["CustomManagerGUID"];
            $userInfo = ErpUserRepository::getUserById($userGuid);
            if (!empty($userInfo)) {
                $item["name"] = $userInfo["UserName"];
                $item["user_guid"] = $userGuid;
                $item["mobile"] = StringHelper::getLastMobilePhone($userInfo["MobilePhone"]);
                $item["email"] = $userInfo["Email"];
                array_push($result["custom_manage"], $item);
            }
        }

        if (empty($result["deliver"]) && !empty($org["DeliverGUID"])) {
            $userGuid = $org["DeliverGUID"];
            $userInfo = ErpUserRepository::getUserById($userGuid);
            if (!empty($userInfo)) {
                $item["name"] = $userInfo["UserName"];
                $item["user_guid"] = $userGuid;
                $item["mobile"] = StringHelper::getLastMobilePhone($userInfo["MobilePhone"]);
                $item["email"] = $userInfo["Email"];
                array_push($result["deliver"], $item);
            }
        }

        //如果为空
        return $result;
    }


    /**
     * 更新联系人信息
     * 批量操作时：客户经理是覆盖，交付顾问是追加
     * 单个项目操作：都是覆盖
     * @param $data
     * @return bool
     * @throws \yii\db\Exception
     */
    public function updateContact($data)
    {
        $orgId = $data["orgId"];
        $projectIds = $data["projectId"];
        $customManageGuid = $data["custom_manage_guid"];
        $deliverGuid = $data["deliver_guid"];
        $isBatch = $data["is_batch"];

        $transaction = ConfigEntity::getDb()->beginTransaction();
        try {

            foreach ($projectIds as $projectId) {
                //保存原有信息
                $ret = $this->saveContactLog($orgId, $projectId);
                if (false === $ret) {
                    throw new \Exception("添加交付信息LOG失败");
                }

                $customManageResult = $this->updateCustomerManager($orgId, $projectId, $customManageGuid);
                if ($customManageResult === false) {
                    throw new \Exception("更新客户经理失败");
                }

                $customManageResult = $this->updateDeliver($orgId, $projectId, $deliverGuid, $isBatch);
                if ($customManageResult === false) {
                    throw new \Exception("添加交付顾问失败");
                }

            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return ErrorInfo::setAndReturn(-1, "保存交付信息失败:" . $e->getMessage());
        }
        return true;
    }

    /**
     * 客户经理，覆盖原有数据
     * @param $orgId
     * @param $projectId
     * @param $customManageGuid
     * @return bool
     * @throws \Exception
     */
    private function updateCustomerManager($orgId, $projectId, $customManageGuid)
    {
        //删除旧数据
        $ret = $this->_projectContactRepository->deleteByProject($orgId, [$projectId], ProjectContactEntity::USER_TYPE_CUSTOME_MANAGER);
        if ($ret === false) {
            throw new \Exception("删除客户经理信息失败");
        }

        $ret = $this->saveContact($orgId, $projectId, $customManageGuid, ProjectContactEntity::USER_TYPE_CUSTOME_MANAGER);
        if (false === $ret) {
            throw new \Exception("添加客户经理信息失败");
        }

        return true;
    }

    private function updateDeliver($orgId, $projectId, $deliverGuid, $isBatch = 0)
    {
        //批量操作是追加，单个项目是覆盖
        if ($isBatch == 0) {
            //非批量操作时，删除旧数据
            $ret = $this->_projectContactRepository->deleteByProject($orgId, [$projectId], ProjectContactEntity::USER_TYPE_DELIVER);
            if ($ret === false) {
                throw new \Exception("删除交付顾问信息失败");
            }
        }

        $ret = $this->saveContact($orgId, $projectId, $deliverGuid, ProjectContactEntity::USER_TYPE_DELIVER);
        if ($ret === false) {
            throw new \Exception("添加交付顾问信息失败");
        }

        return true;
    }

    /**
     * 添加联系人信息以及log
     * @param $orgId
     * @param $projectId
     * @param $userGuids
     * @param $userType
     * @return bool
     * @internal param $addTime
     */
    private function saveContact($orgId, $projectId, $userGuids, $userType)
    {
        foreach ($userGuids as $userGuid) {
            $data = [
                "org_id" => $orgId,
                "project_id" => $projectId,
                "user_guid" => $userGuid,
                "user_type" => $userType,
            ];
            $ret = $this->_projectContactRepository->addContact($data);
            if (false === $ret) {
                return false;
            }
        }
        return true;
    }

    /**
     * 保存log
     * @param $orgId
     * @param $projectId
     * @param $addTime
     * @return bool
     */
    private function saveContactLog($orgId, $projectId)
    {
        $contactData = $this->_projectContactRepository->getList($orgId, $projectId);
        $customeManagerData = [];
        $deliverData = [];
        if (empty($contactData)) {
            return true;
        }
        foreach ($contactData as $contact) {
            $userGuid = $contact["user_guid"];
            $userInfo = ErpUserRepository::getUserById($userGuid);
            $item = [
                "name" => isset($userInfo["UserName"]) ? $userInfo["UserName"] : "",
                "phone" => isset($userInfo["MobilePhone"]) ? $userInfo["MobilePhone"] : "",
                "email" => isset($userInfo["Email"]) ? $userInfo["Email"] : "",
                "user_guid" => $userGuid
            ];
            if ($contact["user_type"] == ProjectContactEntity::USER_TYPE_CUSTOME_MANAGER) {
                array_push($customeManagerData, $item);
            } else {
                array_push($deliverData, $item);
            }
        }

        $log = [
            "org_id" => $orgId,
            "project_id" => $projectId,
            "custome_manager_data" => json_encode($customeManagerData),
            "deliver_data" => json_encode($deliverData),
        ];
        $ret = $this->_changeLogRepository->addLog($log);
        if (false === $ret) {
            return false;
        }
        return true;
    }

    /**
     * 返回操作记录
     * @param $orgId
     * @param $projectId
     * @return array
     */
    public function getContactChangeLog($orgId, $projectId)
    {
        $result = [];
        $data = $this->_changeLogRepository->getLogByProject($orgId, $projectId);
        foreach ($data as $log) {
            $item = [
                "custom_manage" => json_decode($log["custome_manager_data"], true),
                "deliver" => json_decode($log["deliver_data"], true),
                "username" => ErpUserRepository::getUserNameByBuguid($log["created_by"]),
                "create_on" => $log["created_at"]
            ];
            array_push($result, $item);
        }
        return $result;
    }

    /**
     * 更新项目的授权状态
     * @param       $orgCode
     * @param array $projectId
     * @return bool
     */
    public function updateProjectAuthStatus($orgCode, array $projectId)
    {
        if(empty($orgCode)){
            return self::setAndReturn(__LINE__ , 'orgCode不得为空。');
        }
        if (empty($projectId)) {
            return true;
        }

        return $this->_projectRepository->updateProjectAuthStatus($orgCode, $projectId);
    }
}